package com.ukefu.webim.service.sms;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.ukefu.util.HttpClientUtil;
import com.ukefu.util.UKTools;
import com.ukefu.util.sms.SmsService;
import com.ukefu.webim.web.model.SmsResult;
import com.ukefu.webim.web.model.SmsTemplate;
import com.ukefu.webim.web.model.SystemMessage;

@Service("httpsms")
public class HttpSmsImpl implements SmsService {

	@Override
	public SmsResult send(SystemMessage systemMessage, SmsResult result, String phone, SmsTemplate tp, Map<String, Object> values)
			throws Exception {
		try {
			String[] params = systemMessage.getMoreparam().split("\n") ;
			for(String param : params) {
				if(!StringUtils.isBlank(param)) {
					String[] kv = param.split("=") ;
					if(kv.length == 2) {
						String value = kv[1] ;
						if(value.toLowerCase().indexOf("password") >= 0) {
							value = systemMessage.getAppsec() ;
						}else if(value.toLowerCase().indexOf("username") >= 0) {
							value = systemMessage.getAppkey() ;
						}else if(value.toLowerCase().indexOf("smsid") >= 0) {
							value = systemMessage.getTpcode() ;
						}else if(value.toLowerCase().indexOf("mobile") >= 0 || value.toLowerCase().indexOf("phone") >= 0) {
							value = phone ;
						}else if(value.toLowerCase().indexOf("content") >= 0) {
							value = UKTools.getTemplet(tp.getTemplettext(),values) ;
						}else if(value.toLowerCase().indexOf("sign") >= 0) {
							value = systemMessage.getSign() ;
						}else if(value.toLowerCase().indexOf("md5") >= 0) {
							value = UKTools.localMd5(systemMessage.getAppsec());
						}
						/**
						 * 以下去除首尾空格
						 */
						while(value.startsWith(" ") && value.length() > 0) {
							value = value.substring(1) ;
						}
						while(value.endsWith(" ") && value.length() > 0) {
							value = value.substring(0,value.length()) ;
						}
						values.put(kv[0], value) ;
					}
				}
			}
			String checkstr = systemMessage.getResultcheck() ;
			if(StringUtils.isBlank(checkstr)) {
				checkstr = "<Result>0</Result>" ;
			}
			result.setSendresult(HttpClientUtil.sendHttpPost(systemMessage.getUrl(),values));
			if(!StringUtils.isBlank(result.getSendresult()) && result.getSendresult().indexOf(checkstr) >= 0) {
				result.setSendok(true);
			}
		} catch (Exception ex) {
			result.setSendresult(ex.getMessage());
			throw ex;
		} finally {
			result.setSendtime(new Date());
		}
		return result;
	}

	@Override
	public SmsResult checkReach(SmsResult result) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
